<?php

namespace App\Models\Developer;
use App\Http\Common\Globals;
use App\Http\Common\MyUtils;
use App\Models\AreaApp;
use App\Models\BaseHardNew;
use App\Models\BaseOld;
use Illuminate\Support\Str;

/**
 * 开发者 套件 应用
 * Class Developer
 * @package App\Models
 */
class DeveloperPackageApp extends BaseOld
{
    protected $stepLevel = 99;// 审核保存 1正在审核 99审核通过 -1审核不通过
    protected $table = "developer_package_apps";
    public $findAllList = "select a.*,t.name type_name from bf_developer_package_apps a left join bf_developer_package_app_type t on a.type_id=t.id";
    public function myQuery($request)
    {
        parent::myQuery($request); // TODO: Change the autogenerated stub
        $this->sqlSearch($request,'name','like');// 开发者套件名称
        $this->sqlSearch($request,'package_id','=');// 开发者套件id
        $this->sqlSearch($request,'step_level','='
            ,MyUtils::sg($request,'step_level',$this->stepLevel));// 是否审核通过,默认审核通过
    }

    public function list($limit, $page)
    {
        $list = parent::list($limit, $page); // TODO: Change the autogenerated stub
        foreach ($list as $k=>$v){
            if ($v->price){
                $v->price = round($v->price/100,2);
            }
        }
        return $list;
    }

    public function storeDetail($request)
    {
        $detail = parent::storeDetail($request); // TODO: Change the autogenerated stub
        if ($detail){
            if ($detail->price){
                $detail->price = round($detail->price/100,2);
            }
        }
        return $detail;
    }

    public function store($request)
    {
        if (!$request->step_level){
            MyUtils::setRequest($request,'step_level',$this->stepLevel);
        }
        $res = parent::store($request); // TODO: Change the autogenerated stub
        if ($temp = self::find($res)){
            return $temp->update(['app_unique_id'=>md5(Str::random(20).$res,true)]);
        }else{
            Globals::$error = "生成应用唯一码失败";
            return false;
        }
    }
    /**
     * 拥有的所有的小区应用关系
     */
    public function areaApps(){
        return $this->hasMany(AreaApp::class,'app_id');
    }
    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        static::deleting(function($models) {
            $areaApps = $models->areaApps->all();
            foreach ($areaApps as $k=>$v){
                $v->delete();
            }
        });
    }
}
